package com.psq.core.common

import android.app.Activity
import android.app.Application
import android.os.Bundle
import cn.wufuqi.convertmainthread.ConvertMainThread.runOnUiThread
import com.alibaba.android.arouter.launcher.ARouter
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.wukonganimation.action.ActionManager
import java.util.Stack

open class CommonAppContext : Application() {


    companion object {
        private val mActivityStack = Stack<Activity>()
        private lateinit var mInstance: CommonAppContext
        private var mCount = 0
        fun getInstance() = mInstance
    }


    override fun onCreate() {
        super.onCreate()
        mInstance = this

        if (BuildConfig.DEBUG) {
            ARouter.openLog()
            ARouter.openDebug()
        }
        ARouter.init(this)


        //初始化悟空动画
        ActionManager.init(this)

        //设置刷新头
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, _ ->
            ClassicsFooter(context).setDrawableSize(20f)
        }
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, _ ->
            ClassicsHeader(context).setDrawableSize(20f)
        }

        registerActivityLifecycleCallbacks()
    }


    private fun registerActivityLifecycleCallbacks() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                addActivity(activity)
            }

            override fun onActivityStarted(activity: Activity) {
                mCount++
            }

            override fun onActivityResumed(activity: Activity) {
            }

            override fun onActivityPaused(activity: Activity) {
            }

            override fun onActivityStopped(activity: Activity) {
                mCount--
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
            }

            override fun onActivityDestroyed(activity: Activity) {
                finishActivity(activity)
            }
        })
    }


    /**
     * 添加Activity到堆栈
     */
    private fun addActivity(activity: Activity?) {
        if (activity != null) {
            CommonAppContext.mActivityStack.add(activity)
        }
    }

    fun getActivityCount(): Int {
        return CommonAppContext.mActivityStack.size
    }


    /**
     * 结束指定类名的Activity
     */
    fun finishActivity(vararg classZ: Class<*>) {
        runOnUiThread {
            val removeActivity: MutableList<Activity> =
                ArrayList()
            for (i in classZ.indices) {
                val cls = classZ[i]
                val iterator: Iterator<Activity> =
                    CommonAppContext.mActivityStack.iterator()
                while (iterator.hasNext()) {
                    val activity = iterator.next()
                    if (activity.javaClass == cls) {
                        removeActivity.add(activity)
                        activity.finish()
                    }
                }
            }
            for (i in removeActivity.indices) {
                CommonAppContext.mActivityStack.remove(removeActivity[i])
            }
            removeActivity.clear()
            null
        }
    }

    /**
     * 移除指定的Activity
     */
    fun finishActivity(activity: Activity?) {
        if (activity != null) {
            activity.finish()
            CommonAppContext.mActivityStack.remove(activity)
        }
    }

    fun getTopActivity(): Activity? {
        if (CommonAppContext.mActivityStack.isEmpty()) {
            return null
        }
        val size: Int = CommonAppContext.mActivityStack.size
        return if (!CommonAppContext.mActivityStack.isEmpty()) {
            CommonAppContext.mActivityStack.get(size - 1)
        } else {
            null
        }
    }

    /**
     * 判断某Activity是否在栈中
     *
     * @param cls
     * @return
     */
    fun isExist(cls: Class<*>): Boolean {
        if (CommonAppContext.mActivityStack.isEmpty()) {
            return false
        }
        for (i in CommonAppContext.mActivityStack.indices) {
            if (CommonAppContext.mActivityStack.get(i).javaClass == cls) {
                return true
            }
        }
        return false
    }

    fun finishTopActivity() {
        val size: Int = CommonAppContext.mActivityStack.size
        if (size > 1) {
            CommonAppContext.mActivityStack.get(size - 1).finish()
        }
    }

    /**
     * 结束所有Activity
     */
    fun finishAllActivity() {
        val iterator: Iterator<Activity> =
            CommonAppContext.mActivityStack.iterator()
        while (iterator.hasNext()) {
            val activity = iterator.next()
            activity.finish()
        }
        CommonAppContext.mActivityStack.clear()
        System.exit(0)
    }


}